<?php

namespace app\shop\model\recharge;

use app\shop\model\BaseModel;
use app\shop\model\PaymentTradeModel;
use app\shop\model\user\UserModel;
use think\facade\Db;
use think\model\concern\SoftDelete;
use think\model\relation\BelongsTo;
use think\model\relation\HasOne;

class RechargeOrderModel extends BaseModel
{
    use SoftDelete;

    protected $name = 'shop_recharge_order';

    /**
     * 关联用户
     * @return BelongsTo
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(UserModel::class, 'user_id', 'id');
    }

    /**
     * 关联第三方支付
     * @return HasOne
     * @noinspection PhpUnused
     */
    public function paymentTrade(): HasOne
    {
        return $this->hasOne(PaymentTradeModel::class, 'out_trade_no', 'out_trade_no');
    }

    public function cardPayAfter($order_id,$price){

        $array = explode('S',$order_id);
        $user_id = $array[0];
        $cid = $array[1];
        $ligs = Db::name('distribution_log')->where('order_id',$order_id)->find();

        if($ligs){
            throw new FailException('回调失败', null, '订单已支付', ['order_id' => $order_id], true);
        }
        $cardinfo = Db::name('distribution_card')->where('id',$cid)->find();
        $userinfo = Db::name('shop_user')->where('id',$user_id)->find();
        if(isset($userinfo['terminate_time'])){
            if($userinfo['grade_id'] == $cardinfo['distribution_grade_id']){
                $user = [
                    'terminate_time' => $userinfo['terminate_time'] + ($cardinfo['radio']*30*24*3600),
                ];
            }else{
                $user = [
                    'terminate_time' => strtotime("+".$cardinfo['radio']." month", time()),
                    'grade_id' => $cardinfo['distribution_grade_id']
                ];
            }

        }else{
            $user = [
                'terminate_time' => strtotime("+".$cardinfo['radio']." month", time()),
                'grade_id' => $cardinfo['distribution_grade_id']
            ];
        }
        $log = [
            'shop_user_id' => $user_id,
            'distribution_card_id' => $cid,
            'float' => $price,
            'timestamp' => $user['terminate_time'],
            'order_id' => $order_id,
            'create_time' => time()
        ];
        try {
            Db::startTrans();
            Db::name('shop_user')->where('id',$user_id)->update($user);
            Db::name('distribution_log')->where('id',$cid)->insertGetId($log);
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            throw new FailException('回调失败', null, $e, ['order_id' => $order_id], true);
        }
    }
}